package com.wn.ticket.web;

import com.google.zxing.common.BitMatrix;
import com.wn.ticket.common.QRcode;
import com.wn.ticket.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @创建人 NST
 * @创建时间 2022/8/30
 * @描述
 */
@Controller
@RequestMapping("/front")
public class QRcodeController {
    @Autowired
    private OrderService orderService;

    @GetMapping("/QRcode/{OrderNumber}")//获取二维码 后续从jwt中取得用户信息查询他的订单 取订单编号做二维码传输
    public void getQRcodeImage(@PathVariable String OrderNumber, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = null;
        try {
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/jpeg");
            outputStream = response.getOutputStream();
            BitMatrix bitMatrix = QRcode.setBitMatrix(OrderNumber);
            BufferedImage image = QRcode.toBufferedImage(bitMatrix);
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
